package com.yzt.log.aop;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.alibaba.fastjson.JSONObject;
import com.yzt.base.utils.RequestUtil;
import com.yzt.log.entity.SysLog;
import com.yzt.log.service.ISysLogService;

@Aspect
@Component
public class SysLogAsecp {

	@Autowired
	private ISysLogService logService;

	@Pointcut("@annotation(com.yzt.log.aop.SysOperateLog)")
	public void sys_log() {
	}

	@Before("sys_log()")
	public void before(JoinPoint joinPoint) {
		System.out.println("before-------------");
	}

	@Around("sys_log()")
	public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
		Object[] args = joinPoint.getArgs();
		long starTime = System.currentTimeMillis();
		Object result = joinPoint.proceed(args);
		long during = System.currentTimeMillis() - starTime;
		System.out.println("Around-------------" + (during / 1000.0));

		saveSysLog(joinPoint, during);

		return result;
	}

	public void saveSysLog(ProceedingJoinPoint joinPoint, long during) {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
				.getRequest();
		String ip = RequestUtil.getRemoteHost(request);
		Map<String, Object> params = RequestUtil.getParameterMap(request);
		String className = joinPoint.getTarget().getClass().getName();
		String method = joinPoint.getSignature().getName();
		SysLog log = new SysLog();
		log.setIp(ip);
		log.setMethod(className + "." + method);
		log.setParam(JSONObject.toJSONString(params));
		logService.save(log);
	}

	@After("sys_log()")
	public void after(JoinPoint joinpoint) {
		System.out.println("after-------------");
	}
}
